<template>
    <div class="organization-admin-container">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <h1>组织管理员管理</h1>
                </div>
            </template>
            <!-- 新增组织管理员按钮和搜索框 -->
            <div class="header-actions">
                <el-button type="primary" @click="openDialog">新增组织管理员</el-button>
                <el-input v-model="searchUsername" placeholder="请输入用户名" style="width: 300px; margin-left: 20px"
                    @input="handleSearch">
                    <template #append>
                        <el-button @click="clearSearch">清除</el-button>
                    </template>
                </el-input>
            </div>
            <!-- 组织管理员列表 -->
            <el-table :data="organizationAdmins.content" border stripe style="width: 100%">
                <el-table-column prop="id" label="ID" />
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="password" label="密码" />
                <el-table-column prop="role" label="类型" />
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button type="primary" :icon="Edit" @click.stop="editOrganizationAdmin(row)"></el-button>
                        <el-button type="danger" :icon="Delete" @click.stop="deleteOrganizationAdmin(row.id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :total="organizationAdmins.totalElements" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />

            <!-- 新增/编辑组织管理员对话框 -->
            <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑组织管理员' : '新增组织管理员'">
                <el-form :model="form" label-width="120px">
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="用户名">
                                <el-input v-model="form.username" :disabled="isEditMode" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="密码">
                                <div class="mt-4">
                                    <el-input v-model="form.password" type="password" :disabled="isEditMode">
                                        <template #append>
                                            <el-button v-if="isEditMode" @click="confirmResetPassword">重置密码</el-button>
                                        </template>
                                    </el-input>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="类型">
                                <el-select v-model="form.role" placeholder="请选择类型">
                                    <el-option label="一级管理员" value="first" />
                                    <el-option label="二级管理员" value="second" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <template #footer>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">保存</el-button>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from '../axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit } from '@element-plus/icons-vue';

// 组织管理员列表
const organizationAdmins = ref({
    content: [], // 当前页的组织管理员数据
    totalElements: 0, // 总数据量
    size: 5, // 每页大小
    number: 1, // 当前页码（从 1 开始）
});

// 表单数据
const form = ref({
    id: null,
    username: '',
    password: '',
    role: '',
});

// 对话框是否可见
const dialogVisible = ref(false);

// 是否为编辑模式
const isEditMode = ref(false);

// 分页相关状态
const currentPage = ref(1); // 当前页码（从 1 开始）
const pageSize = ref(5); // 每页大小

// 搜索关键字
const searchUsername = ref('');

// 获取所有组织管理员
const fetchOrganizationAdmins = async (page = 1, size = 5, username = '') => {
    try {
        const response = await axios.get('/organization-admin/search', {
            params: { page, size, username },
        });
        organizationAdmins.value = response.data;
    } catch (error) {
        ElMessage.error('获取组织管理员列表失败');
    }
};

// 打开对话框
const openDialog = () => {
    isEditMode.value = false; // 设置为新增模式
    form.value = { id: null, username: '', password: '', role: '' }; // 清空表单
    dialogVisible.value = true;
};

// 编辑组织管理员
const editOrganizationAdmin = (row) => {
    isEditMode.value = true; // 设置为编辑模式
    form.value = { ...row }; // 填充表单
    dialogVisible.value = true;
};

// 确认重置密码
const confirmResetPassword = () => {
    ElMessageBox.confirm('确定要重置密码为初始密码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        form.value.password = '123456'; // 重置密码
        ElMessage.success('密码已重置为初始密码');
    }).catch(() => {
        // 用户取消操作
    });
};

// 表单验证
const validateForm = () => {
    if (!form.value.username || !form.value.password || !form.value.role) {
        ElMessage.error('请填写所有必填字段');
        return false;
    }
    return true;
};

// 提交表单（新增或更新）
const submitForm = async () => {
    if (!validateForm()) {
        return; // 如果表单验证失败，直接返回
    }
    try {
        if (isEditMode.value) {
            // 更新组织管理员
            const response = await axios.put(`/organization-admin/${form.value.id}`, form.value);
            const index = organizationAdmins.value.content.findIndex((admin) => admin.id === form.value.id);
            if (index !== -1) {
                organizationAdmins.value.content.splice(index, 1, response.data);
            }
            ElMessage.success('组织管理员更新成功');
        } else {
            // 新增组织管理员
            const response = await axios.post('/organization-admin', form.value);
            organizationAdmins.value.content.push(response.data);
            ElMessage.success('组织管理员新增成功');
        }
        dialogVisible.value = false; // 关闭对话框
        fetchOrganizationAdmins(currentPage.value, pageSize.value, searchUsername.value); // 刷新当前页的组织管理员列表
    } catch (error) {
        ElMessage.error(error.response?.data || '操作失败');
    }
};

// 删除组织管理员
const deleteOrganizationAdmin = async (id) => {
    try {
        await axios.delete(`/organization-admin/${id}`);
        organizationAdmins.value.content = organizationAdmins.value.content.filter((admin) => admin.id !== id);
        ElMessage.success('组织管理员删除成功');
    } catch (error) {
        ElMessage.error('组织管理员删除失败');
    }
};

// 处理每页大小变化
const handleSizeChange = (size) => {
    pageSize.value = size;
    fetchOrganizationAdmins(1, size, searchUsername.value); // 每页大小变化时，加载第一页数据
};

// 处理页码变化
const handleCurrentChange = (page) => {
    currentPage.value = page;
    fetchOrganizationAdmins(page, pageSize.value, searchUsername.value); // 加载对应页的数据
};

// 处理搜索
const handleSearch = () => {
    fetchOrganizationAdmins(1, pageSize.value, searchUsername.value); // 搜索时，加载第一页数据
};

// 清除搜索
const clearSearch = () => {
    searchUsername.value = ''; // 清空搜索框内容
    fetchOrganizationAdmins(1, pageSize.value); // 重新加载所有数据
};

// 初始化时加载第一页数据
onMounted(() => {
    fetchOrganizationAdmins();
});
</script>

<style scoped>
.organization-admin-container {
    max-width: 1200px;
    margin: 20px auto;
    padding: 20px;
}

.card-header {
    text-align: center;
}

.header-actions {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}
::v-deep.el-table th,
::v-deep.el-table td {
  height: 40px;
  line-height: 40px;
  text-align: center;
}
</style>